<?php

namespace app\admin\controller\system;

use albert\services\CacheService;
use app\admin\controller\AuthController;
use app\model\system\SystemConfig;
use app\model\system\SystemConfigTab;
use albert\services\FormBuilder;
use albert\services\JsonService;
use albert\services\upload\Upload;
use albert\services\UtilService;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

/**
 * 系统配置控制器
 * Class ConfigController
 * @package app\admin\controller\system
 */
class ConfigController extends AuthController
{
    /**
     * 系统配置展示页
     * Author: Albert3306
     * Date: 2021/7/2
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function index(): string
    {
        [$type, $tab_id, $children_tab_id] = UtilService::param([
            ['type', 0], // 配置类型
            ['tab_id', 1], // 当前分类ID
            ['children_tab_id', null], // 当前子集分类ID
        ], $this->request, true);

        if ($type == 3) { // 其它分类
            $config_tab = null;
        } else {
            $config_tab = SystemConfig::getConfigTabAll($type); // 获取一级 tab
        }
        $children_config_tab = SystemConfig::getConfigChildrenTabAll($tab_id); // 获取二级 tab

        if (!$children_tab_id && $children_config_tab) {
            $children_tab_id = $children_config_tab[0]['id'];
        }

        if ($children_tab_id) {
            $tid = $children_tab_id;
        } else {
            $tid = $tab_id;
        }

        // 获取分类配置参数
        $list = SystemConfig::getAll($tid);
        $f = SystemConfig::builder_config_from_data($list); // 生产表单json
        $form = FormBuilder::make_post_form('编辑配置', $f, '/admin/system/config/modify');
        return $this->fetch('system/config/index', compact('tab_id', 'children_tab_id', 'config_tab', 'children_config_tab', 'form', 'list'));
    }

    /**
     * 修改配置值保存
     * Author: Albert3306
     * Date: 2021/7/2
     * @return string
     */
    public function modifyConfigValue(): string
    {
        $post = $this->request->post();
        foreach ($post as $k => $v) {
            if (is_array($v)) {
                $res = SystemConfig::initWhere(['name' => $k])->column('upload_type', 'type');
                foreach ($res as $kk => $vv) {
                    if ($kk == 'upload') {
                        if ($vv == 1 || $vv == 3) {
                            $post[$k] = $v[0];
                        }
                    }
                }
            }
        }
        foreach ($post as $k => $v) {
            SystemConfig::edit(['value' => json_encode($v)], $k, 'name');
        }
        CacheService::clear();
        return JsonService::success('修改成功！');
    }

    /**
     * 添加
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     */
    public function create(): string
    {
        $data = UtilService::param([
            ['type', ''],
            ['tab_id', 1],
        ], $this->request);

        // 构建表单
        $f = [];
        $f[] = FormBuilder::select('config_tab_id', '分类', $data['tab_id'])->setOptions(SystemConfigTab::getTabTree())->filterable(1);
        $f[] = FormBuilder::select('input_type', '类型')->setOptions(SystemConfig::texttype());
        $f[] = FormBuilder::input('info', '配置名称')->autofocus(1);
        $f[] = FormBuilder::input('name', '字段变量')->placeholder('例如：site_url');
        $f[] = FormBuilder::input('desc', '配置简介');

        // 不同类型字段
        switch ($data['type']) {
            case 0: // 文本框
                SystemConfig::createInputRule($f);
                break;
            case 1: // 多行文本框
                SystemConfig::createTextAreaRule($f);
                break;
            case 2: // 单选框
                SystemConfig::createRadioRule($f);
                break;
            case 3: // 文件上传
                SystemConfig::createUploadRule($f);
                break;
            case 4: // 多选框
                SystemConfig::createCheckboxRule($f);
                break;
            case 5: // 下拉框
                SystemConfig::createSelectRule($f);
                break;
        }
        $f[] = FormBuilder::number('sort', '排序');
        $f[] = FormBuilder::radio('status', '状态', 1)->options(SystemConfig::formStatus());
        $form = FormBuilder::make_post_form('添加字段', $f, '/admin/system/config/save', 3);
        return $this->fetch('system/config/create', [
            'form' => $form,
            'get' => request()->param()
        ]);
    }

    /**
     * 添加保存
     * Author: Albert3306
     * Date: 2021/6/30
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function save(): string
    {
        $data = UtilService::param([
            ['sort', 0],
            ['type', 0],
            ['info', ''],
            ['desc', ''],
            ['high', ''],
            ['name', ''],
            ['width', ''],
            ['value', ''],
            ['status', 1],
            ['required', ''],
            ['parameter', ''],
            ['input_type', ''],
            ['upload_type', ''],
            ['config_tab_id', 0],
        ], $this->request);
        if (!$data['info']) return JsonService::fail('请输入配置名称！');
        if (!$data['name']) return JsonService::fail('请输入字段名称！');
        if ($data['name']) {
            $oneConfig = SystemConfig::getOneConfig('name', $data['name']);
            if (!empty($oneConfig)) return JsonService::fail('请重新输入字段名称,之前的已经使用过了！');
        }
        if (!$data['desc']) return JsonService::fail('请输入配置简介！');
        if ($data['sort'] < 0) {
            $data['sort'] = 0;
        }
        if ($data['type'] == 'text') {
            if (!SystemConfig::validDateTextRole($data)) return JsonService::fail(SystemConfig::getErrorInfo());
        }
        if ($data['type'] == 'textarea') {
            if (!SystemConfig::validDateTextareaRole($data)) return JsonService::fail(SystemConfig::getErrorInfo());
        }
        $data['parameter'] = htmlspecialchars_decode($data['parameter']);
        if ($data['type'] == 'radio' || $data['type'] == 'checkbox') {
            if (!$data['parameter']) return JsonService::fail('请输入配置参数');
            if (!SystemConfig::validDateRadioAndCheckbox($data)) return JsonService::fail(SystemConfig::getErrorInfo());
            $data['value'] = json_encode($data['value']);
        }
        SystemConfig::create($data);
        Cache::clear();
        return JsonService::successful('添加菜单成功！');
    }

    /**
     * 编辑
     * Author: Albert3306
     * Date: 2021/7/1
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function edit($id): string
    {
        $config = SystemConfig::get($id)->getData();
        if (!$config) return JsonService::fail('数据不存在！');

        // 构建表单
        $f = [];
        $f[] = FormBuilder::input('name', '字段变量', $config['name'])->disabled(1);
        $f[] = FormBuilder::hidden('type', $config['type']);
        $f[] = FormBuilder::select('config_tab_id', '分类', (string)$config['config_tab_id'])->setOptions(SystemConfigTab::getTabTree())->filterable(1);
        $f[] = FormBuilder::input('info', '配置名称', $config['info'])->autofocus(1);
        $f[] = FormBuilder::input('desc', '配置简介', $config['desc']);

        // 判断配置类型
        switch ($config['type']) {
            case 'text':
                $config['value'] = json_decode($config['value'], true);
                $f[] = FormBuilder::select('input_type', '类型', $config['input_type'])->setOptions(SystemConfig::textType());
                $f[] = FormBuilder::input('value', '默认值', $config['value']);
                if (!empty($config['required'])) {
                    $f[] = FormBuilder::number('width', '文本框宽(%)', $config['width']);
                    $f[] = FormBuilder::input('required', '验证规则', $config['required'])->placeholder('多个请用,隔开例如：required:true,url:true');
                }
                break;
            case 'textarea':
                $config['value'] = json_decode($config['value'], true);
                // 多行文本
                if (!empty($config['high'])) {
                    $f[] = FormBuilder::textarea('value', '默认值', $config['value'])->rows(5);
                    $f[] = FormBuilder::number('width', '文本框宽(%)', $config['width']);
                    $f[] = FormBuilder::number('high', '多行文本框高(%)', $config['high']);
                } else {
                    $f[] = FormBuilder::input('value', '默认值', $config['value']);
                }
                break;
            case 'radio':
                $config['value'] = json_decode($config['value'], true);
                $parameter = explode("\n", htmlspecialchars_decode($config['parameter']));
                $options = [];
                if ($parameter) {
                    foreach ($parameter as $v) {
                        $data = explode("=>", $v);
                        $options[] = ['label' => $data[1], 'value' => $data[0]];
                    }
                    $f[] = FormBuilder::radio('value', '默认值', $config['value'])->options($options);
                }
                // 单选和多选参数配置
                if (!empty($config['parameter'])) {
                    $f[] = FormBuilder::textarea('parameter', '配置参数', $config['parameter'])->placeholder("参数方式例如:\n1=白色\n2=红色\n3=黑色");
                }
                break;
            case 'checkbox':
                $config['value'] = json_decode($config['value'], true) ?: [];
                $parameter = explode("\n", htmlspecialchars_decode($config['parameter']));
                $options = [];
                if ($parameter) {
                    foreach ($parameter as $v) {
                        $data = explode("=>", $v);
                        $options[] = ['label' => $data[1], 'value' => $data[0]];
                    }
                    $f[] = FormBuilder::checkbox('value', '默认值', $config['value'])->options($options);
                }
                // 单选和多选参数配置
                if (!empty($config['parameter'])) {
                    $f[] = FormBuilder::textarea('parameter', '配置参数', $config['parameter'])->placeholder("参数方式例如:\n1=白色\n2=红色\n3=黑色");
                }
                break;
            case 'upload':
                if ($config['upload_type'] == 1) {
                    $config['value'] = json_decode($config['value'], true);
                    $f[] = FormBuilder::frameImageOne('value', '图片', '/admin/widget/images?fodder=value', (string)$config['value'])->icon('image')->width('100%')->height('550px');
                } elseif ($config['upload_type'] == 2) {
                    $config['value'] = json_decode($config['value'], true) ?: [];
                    $f[] = FormBuilder::frameImages('value', '多图片', '/admin/widget/images?fodder=value', $config['value'])->maxLength(5)->icon('images')->width('100%')->height('550px')->spin(0);
                } else {
                    $config['value'] = json_decode($config['value'], true);
                    $f[] = FormBuilder::uploadFileOne('value', '文件', '/admin/system/config/file_upload', $config['value'])->name('file');
                }
                // 上传类型选择
                if (!empty($config['upload_type'])) {
                    $f[] = FormBuilder::radio('upload_type', '上传类型', $config['upload_type'])->options([['value' => 1, 'label' => '单图'], ['value' => 2, 'label' => '多图'], ['value' => 3, 'label' => '文件']]);
                }
                break;
        }
        $f[] = FormBuilder::number('sort', '排序', $config['sort']);
        $f[] = FormBuilder::radio('status', '状态', $config['status'])->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]);

        $form = FormBuilder::make_post_form('编辑字段', $f, '/admin/system/config/update/' . $id);
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 编辑保存
     * Author: Albert3306
     * Date: 2021/7/1
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function update($id): string
    {
        $type = $this->request->post('type');
        if ($type == 'text' || $type == 'textarea' || $type == 'radio' || ($type == 'upload' && (request()->post('upload_type') == 1 || request()->post('upload_type') == 3))) {
            $value = request()->post('value');
        } else {
            $value = request()->post('value/a');
        }
        $data = UtilService::param([
            ['sort', 0],
            ['info', ''],
            ['desc', ''],
            ['status', ''],
            ['value', $value],
            ['required', ''],
            ['parameter', ''],
            ['input_type', ''],
            ['upload_type', ''],
            ['config_tab_id', ''],
        ], $this->request);
        $data['value'] = htmlspecialchars_decode(json_encode($data['value']));
        $data['parameter'] = htmlspecialchars_decode($data['parameter']);
        if (!SystemConfig::get($id)) return JsonService::fail('数据不存在！');
        SystemConfig::edit($data, $id);
        return JsonService::successful('修改成功！');
    }

    /**
     * 文件上传
     * Author: Albert3306
     * Date: 2021/7/1
     * @return string
     */
    public function file_upload(): string
    {
        $upload = new Upload('local');
        $res = $upload->to('config/file')->validate()->move($this->request->file('file'));
        if ($res === false) return JsonService::fail('上传失败：' . $upload->getError());
        return JsonService::successful('上传成功!', ['filePath' => $res->filePath]);
    }

    /**
     * 删除子字段
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $id
     * @return string
     */
    public function delete($id): string
    {
        if (!SystemConfig::del($id)) {
            return JsonService::fail(SystemConfig::getErrorInfo('删除失败，请稍候再试！'));
        } else {
            CacheService::clear();
            return JsonService::successful('删除成功！');
        }
    }
}